package The08;

import org.junit.Test;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Objects;
import java.util.function.Predicate;

/**
 * @Author XiaoKe
 * @Date 2020/4/29 9:28
 * @Description 遍历集合
 */
public class CollectionEach {

    @Test // 使用Lambda表达式来遍历集合
    public void test1() {
        HashSet<String> books = new HashSet<>();
        books.add("java");
        books.add("c++");
        books.add("python");
        books.forEach(obj -> System.out.println("迭代集合元素："+ obj));
    }

    @Test // 使用iterator遍历集合元素
    public void test2() {
        HashSet<String> books = new HashSet<>();
        books.add("java");
        books.add("c++");
        books.add("python");
        // 获取books集合对应的迭代器
        Iterator<String> it = books.iterator();
        while (it.hasNext()) {
            // it.next()方法返回的数据类型是Object类型，所有需要强制转换类型
            String book = (String) it.next();
            System.out.println(book);
            if (book.equals("java")) {
                it.remove();
            }
            // 对book赋值不会改变集合元素本身
            book = "测试";
        }
        System.out.println(books);
    }

    @Test // 使用Lambda表达式遍历集合元素
    public void test3() {
        HashSet<String> books = new HashSet<>();
        books.add("java");
        books.add("c++");
        books.add("python");
        // 获取books集合对应的迭代器
        Iterator<String> it = books.iterator();
        it.forEachRemaining(obj -> System.out.println("迭代集合：" + obj));

    }

    @Test // 使用foreach循环遍历集合元素
    public void test4() {
        HashSet<String> books = new HashSet<>();
        books.add("java");
        books.add("c++");
        books.add("python");

        for (String obj : books) {
            System.out.println(obj);
        }
    }

    @Test // 使用Predicate操作集合（根据条件过滤）
    public void test5() {
        HashSet<String> books = new HashSet<>();
        books.add("java");
        books.add("c++");
        books.add("python");
        books.add("android");
        // 使用lambda表达式过滤集合
        books.removeIf(ele -> ((String) ele).length() < 5);
        System.out.println(books);
        // 统计书名包含"o"子串的图书数量
        System.out.println(calAll(books, ele -> ((String) ele).contains("o")));
    }
    public static int calAll(Collection books, Predicate p) {
        int total = 0;
        for (Object book : books) {
            // 判断该对象是否满足Predicate指定的条件
            if (p.test(book)) {
                total++;
            }
        }
        return total;
    }
}
